<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2021/3/31
 * Time: 1:00
 */

namespace app\adminapi\validate;

use app\common\model\Admin;

/**
 * 管理员登录验证
 * Class Login
 * @package app\apiadmin\validate
 */
class Login extends Base
{
    protected $rule = [
        'username' => 'require|usernameExists',
        'password' => 'require|max:20|passwordEquality|adminStatus',
        'code' => 'require|max:4|codeEquality',
        'rememberPass' => 'require|rememberPassEquality'
    ];

    protected $message = [
        'mobile.require' => '用户名必须',
        'mobile.usernameExists' => '用户不存在',
        
        'password.require' => '密码必须',
        'password.max' => '密码不能超过20位',
        'password.passwordEquality' => '用户名密码不匹配',
        'password.adminStatus' => '管理员已被禁用',

        'code.require' => '验证码必须',
        'code.max' => '验证码不能超过4位',
        'code.codeEquality' => '验证码错误',

        'rememberPass.require' => '请选择是否记住密码',
        'rememberPass.rememberPassEquality' => '记住密码参数值错误',
    ];

    /**
     * 用户名是否存在
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function usernameExists($value, $rule, $data)
    {
        if (Admin::get(['username' => $value])) return true;
        return false;
    }

    /**
     * 密码是否正确
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function passwordEquality($value, $rule, $data)
    {
        $admin = Admin::get(['username' => $data['username']]);
        if($admin['password']!=Admin::getEncryptPassword($data['password'], $admin['salt'])) return false;
        return true;
    }

    protected function adminStatus($value, $rule, $data)
    {
        $admin = Admin::get(['username' => $data['username']]);
        if($admin['status']!='normal') return false;
        return true;
    }

    /**
     * 记住密码值是否正确
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     */
    protected function rememberPassEquality($value, $rule, $data)
    {
        $arr = [0, 1];
        if(!in_array($value, $arr)) return false;
        return true;
    }

}